<?php

class sign extends bhCommon {

    public $signin_days = array(
        1 => array(
            'key' => 'signin_one_day',
            'default' => 2
        ),
        2 => array(
            'key' => 'signin_two_day',
            'default' => 2
        ),
        3 => array(
            'key' => 'signin_three_day',
            'default' => 2
        ),
        4 => array(
            'key' => 'signin_four_day',
            'default' => 2
        ),
        5 => array('key' => 'signin_five_day',  'default' => 2),
        6 => array('key' => 'signin_six_day',  'default' => 2),
        7 => array('key' => 'signin_seven_day',  'default' => 2)
    );

    /**
     *
     */
    public function index()
    {

        $reward = $this->signin_days;
        foreach ($reward as & $val) {
            $val['integral'] = getConfig($val['key'], 0);
        }

        $sgin = array(
            'is_sgin' => $this->bargain->is_sign($this->member['id']),
            'reward' => $reward,
            'is_double' => getConfig('is_double', 1),
            'is_sign_double' => $this->bargain->is_sign_double($this->member['id'])
        );
        $continuity = $this->bargain->get_signin($this->member['id']);
        $days = $continuity > 0 ? (($continuity % 7) ? : 7) : 0;
        $sgin['days'] = $days;

        $config = array(
            'integral_name' => getConfig('integral_name', '积分'),
            'integral_text' => getConfig('integral_text', '每日签到获取积分，兑换更多商品'),
            'sgin_subscribe' => getConfig('sign_subscribe'),
            'adUnitId' => getConfig('video_id'),
            'screen_ad' => getConfig('screen_id'),
            'sigin_title' => getConfig('sigin_title', '签到'),
            'red_grant_hour' => getConfig('red_grant_hour', 0),
            'red_grant_minute' => getConfig('red_grant_hour', 0),
            'open_bag' => getConfig('open_bag', 1),
            'auth_integral' => getConfig('auth_integral', 0),
            'auth_phone' => getConfig('auth_phone', 0),
            'banner_id' => getConfig('sign_ad')
        );
        $config['red_grant_hour'] < 10 && $config['red_grant_hour'] = '0'. $config['red_grant_hour'];
        $config['red_grant_minute'] < 10 && $config['red_grant_minute'] = '0'. $config['red_grant_minute'];


        $time = strtotime(date('Y-m-d', time())) + 86400;
        $remind = p_get('remind', array('member_id' => $this->member['id'], 'remind_day' => $time, 'type' => 1));


        $red_bag = p_getall('red_bag', array(), array(), 'sort desc', 4);
        $is_red = false;

        if ($red_bag) {
            $same_day = strtotime(date('Y-m-d'));
            foreach ($red_bag as & $v) {
                $w = array(
                    'member_id' => $this->member['id'],
                    'red_bag_id' => $v['id'],
                    'same_day' => $same_day
                );
                if ($v['info'] = p_get('member_red_bag', $w)) {
                    $is_red = true;
                }
            }
        }


        $integral_goods = p_getall('integral_goods', array('status' => 1, 'is_delete' => 1, 'is_home' => 2), array(), array(), 'sort desc');
        if ($integral_goods) {
            foreach ($integral_goods as & $g) {
                if ($g['type'] == 2) {
                    if (empty($g['goods_name']) || empty($g['cover_image'])) {
                        $pdd = $this->bargain->pdd_details($g['relation_goods_id']);
                        $g['goods_name'] = $pdd['goods_name'];
                        $g['cover_image'] = $pdd['goods_thumbnail_url'];

                        p_update('integral_goods', array('goods_name' => $pdd['goods_name'], 'cover_image' => $pdd['goods_thumbnail_url']), array('id' => $g['id']));
                    }


                } else {
                    $g['cover_image'] = getImage($g['cover_image']);
                }
            }
        }

        $images = array(
            'red_bg' => $this->image_url . 'red.png'
        );

        $data = array(
            'sgin' => $sgin,
            'config' => $config,
            'continuity' => $continuity,
            'red_bag' => $red_bag,
            'integral_goods' => $integral_goods,
            'is_red' => $is_red,
            'images' => $images,
            'member' => $this->member,
            'is_remind' => !empty($remind),
            'is_auth' => $this->is_auth
        );

        $this->json($data);
    }


    public function task()
    {
        $sql = "SELECT * FROM " . prefix('task') . " WHERE `position` = 2 OR `position` = 3"  . get_uniacid() .  "  order by sort desc ";
        $task = p_fetchall($sql);
        if ($task) {
            $same_day = strtotime(date('Y-m-d'));
            foreach ($task as & $line) {
                $w = array(
                    'member_id' => $this->member['id'],
                    'task_id' => $line['id'],
                    'same_day' => $same_day
                );
                $m = p_get('task_member', $w);
                $line['state'] = 1;
                $line['is_succ'] = 1;
                $line['succ_num'] = 0;

                $line['num'] = 0;

                if (!empty($m)) {

                    $line['num'] = $m['number'];

                    if (in_array($line['type'], array(1,3))) {
                        $line['state'] = 3;
                        $line['succ_num'] = 1;
                    } else {
                        $line['succ_num'] = $m['number'];
                        $line['state'] = $m['number'] >= $line['number'] ? 3 : 1;
                    }
                } else {
                    if ($line['type'] == 1) {
                        $sql = "SELECT COUNT(*) FROM " . prefix('luck_participate') . " WHERE member_id={$this->member['id']} AND created >= {$same_day}";
                        $num = p_fetchcolumn($sql) ? : 0;

                        if ($line['number'] <= $num) {
                            $line['state'] = 2;
                            $line['num'] = $line['number'];
                        } else {
                            $line['num'] = $num;
                        }

                    }
                }
            }
        }
        $data = array(
            'task' => $task,
            'member' => $this->member
        );
        $this->json($data);
    }



    /**
     * 签到提醒
     */
    public function remind()
    {
        $time = strtotime(date('Y-m-d', time())) + 86400;
        $remind = p_get('remind', array('member_id' => $this->member['id'], 'remind_day' => $time, 'type' => 1));

        if ($remind) {
            p_delete('remind', array('id' => $remind['id']));
            $is_remind = false;
        } else {
            $data = array(
                'member_id' => $this->member['id'],
                'remind_day' => $time,
                'type' => 1,
                'created' => time()
            );
            p_insert('remind', $data);
            $is_remind = true;
        }
        $this->json(array('is_remind' => $is_remind));
    }


    /**
     * 签到翻倍
     */
    public function double()
    {
        if ($this->bargain->is_sign_double($this->member['id'])) {
            $this->json();
        }
        $days = $this->bargain->get_signin($this->member['id']);
        $d = ($days % 7) ? : 7;
        $integral = getConfig($this->signin_days[$d]['key'], 0);

        if ($this->bargain->change_integral($this->member['id'], $integral, 2)) {
            $this->json();
        }
        $this->json('翻倍失败', 2);
    }


    /**
     * 签到
     */
    public function siginIn()
    {
        if ($this->bargain->is_sign($this->member['id'])) {
            $this->json();
        }
        $days = $this->bargain->get_signin($this->member['id']) + 1;
        //$days = $days > 7 ? 1 : $days;
        $days = ($days % 7) ? : 7;
        $integral = getConfig($this->signin_days[$days]['key'], 0);

        $days = $this->bargain->signin($this->member['id'], $integral);
        if (!$days) {
            $this->json($this->bargain->error, 2);
        }

        $data = array(
            'days' => $days,
            'sign_integral' => $integral
        );
        $this->json($data);
    }


    /**
     * 积分明细
     */
    public function log()
    {
        $p = $this->get('p', 1);
        $page_size = 10;
        $limit = ($p - 1) * $page_size;
        $log = p_getall('integral_log', array('member_id' => $this->member['id']), array(),'', array('id desc'), "{$limit}, {$page_size}");

        if ($log) {
            $msg = array(
                1 => '签到',
                2 => '签到翻倍',
                3 => '兑换礼品',
                4 => '完成任务',
                5 => '兑换道具',
                6 => '兑换红包',
                7 => '绑定手机号',
                8 => '授权个人信息',
                9 => '邀请好友',
                10 => '兑换积分商品',
                11 => '获取群二维码',
            );
            foreach ($log as & $v) {
                $v['created'] = date('Y-m-d', $v['created']);
                $v['msg'] = $msg[$v['type']];

                $v['mold'] = in_array($v['type'], array(1,2,4,7,8,9)) ? 1 : 2;
            }
        }
        $data = array(
            'log' => $log
        );
        $this->json($data);
    }


    /**
     * 积分商品
     */
    public function details()
    {
        $id = intval($this->get('id'));

        $goods = p_get('integral_goods', array('id' => $id, 'status' => 1, 'is_delete' => 1));
        if (empty($goods)) {
            $this->json('商品不存在或者已下架', 0);
        }
        if (!empty($goods['image'])) {
            $goods['image'] = json_decode($goods['image']);
            $goods['image'] = array_map('getImage', $goods['image']);
        }

        $goods['share_title'] = str_replace('{name}', $this->member['nickname'], $goods['share_title']);


        $order = p_getall('order', array('goods_id' => $id, 'is_pay' => 2), array(), '', 'id desc', 10);
        if ($order) {
            foreach ($order as & $value) {
                $value['member'] = p_get('memberinfo', array('id' => $value['member_id']));
                $value['formatTime'] = formatTime($value['created']);
            }
        }


        $buy_status = 1;
        $count = p_getcolumn('order', array('goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
        if ($count >= $goods['inventory']) {
            $buy_status = 2;
            $goods['inventory'] = 0;
        } else {
            $goods['inventory'] = $goods['inventory'] - $count;
        }

        if ($buy_status == 1 && $goods['allow_number'] > 0) {
            $buy_num = p_getcolumn('order', array('member_id' => $this->member['id'], 'goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
            $buy_status = $buy_num >= $goods['allow_number'] ? 3 : 1;
        }
        if ($buy_status == 1) {
            $buy_status = $this->member['integral'] < $goods['exchange_number'] ? 4 : 1;
        }

        $goods['cover_image'] = getImage($goods['cover_image']);

        $address = p_get('address', array('member_id' => $this->member['id']));

        $config = array(
            'integral_name' => getConfig('integral_name', '积分'),
            'goods_flow_group' => getConfig('goods_ad', 'adunit-96c594f54064b9c5'),
            //'ad_type' => getConfig('ad_type', 1),
        );
        $data = array(
            'goods' => $goods,
            'config' => $config,
            'address' => $address,
            'order' => $order,
            'buy_status' => $buy_status
        );
        $this->json($data);
    }



    public function order()
    {
        $order = p_getall('integral_order', array('member_id' => $this->member['id'], 'is_pay' => 2), array(),'', array('id desc')) ? : array();
        if ($order) {
            $status = array(
                1 => '未发货',
                2 => '已发货',
                3 => '已完成',
                4 => '已取消'
            );
            foreach ($order as & $value) {
                $value['goods'] = p_get('integral_goods', array('id' => $value['goods_id']));

                if ($value['type'] == 2) {
                    $pdd = $this->bargain->pdd_details($value['relation_goods_id']);
                    $value['goods']['goods_name'] = $pdd['goods_name'];
                    $value['goods']['img'] = $pdd['goods_thumbnail_url'];
                } else {
                    $value['goods']['img'] = getImage($value['goods']['cover_image']);
                }

                $value['created'] = date('Y-m-d H:i:s', $value['created']);
                $value['status_msg'] = $status[$value['status']];
            }
        }
        $images = array(
            'my_orders_nodata' => $this->image_url . 'my_orders_nodata.png',
            'my_express_icon' => $this->image_url . 'my_express_icon.png',
            'address_locate' => $this->image_url . 'address_locate.png',
            'attention' => $this->image_url . 'attention.png'
        );
        $data = array(
            'orders' => $order,
            'currency_name' => getConfig('integral_name'),
            'images' => $images
        );
        $this->json($data);
    }


    /**
     * 领取
     */
    public function receive()
    {
        $id = $this->get('id');
        $task = p_get('task', array('id' => $id));

        if (empty($task)) {
            $this->json('任务不存在', 2);
        }
        $same_day = strtotime(date('Y-m-d'));

        if ($task['type'] == 1) {
            $sql = "SELECT COUNT(*) FROM " . prefix('luck_participate') . " WHERE member_id={$this->member['id']} AND created >= {$same_day}";
            $num = p_fetchcolumn($sql) ? : 0;

            if ($task['number'] > $num) {
                $this->json('任务还未完成哦~', 2);
            }

        } elseif ($task['type'] == 4) {
            $sql = "SELECT COUNT(*) FROM " . prefix('member') . " WHERE parent_id={$this->member['id']} AND (nickname!='' OR headimgurl!='') AND created >= {$same_day}";
            $num = p_fetchcolumn($sql) ? : 0;

//            if ($task['number'] > $num) {
//                $this->json('任务还未完成哦~', 2);
//            }
        }
        $task_member = p_get('task_member', array('member_id' => $this->member['id'], 'task_id' => $task['id'], 'same_day' => $same_day));

        if ($task_member && (in_array($task['type'], array(1, 3, 4)) || ($task['type'] == 2 && $task_member['number'] >= $task['number']))) {
            $this->json();
        }
        pdo_begin();
        try{
            if (!$this->bargain->change_integral($this->member['id'], $task['integral'], 4, $task['title'])) {
                throw new Exception($this->bargain->error);
            }
            if ($task_member && $task['type'] == 2) {
                if (!p_update('task_member', array('number' => $task_member['number'] + 1), array('id' => $task_member['id']))) {
                    throw new Exception('奖励领取失败~');
                }
            } else {
                $insert = array(
                    'member_id' => $this->member['id'],
                    'task_id' => $id,
                    'same_day' => $same_day,
                    'created' => time()
                );
                if ($task['type'] == 1) {
                    $insert['number'] = $task['number'];
                }
                if (!p_insert('task_member', $insert)) {
                    throw new Exception('奖励领取失败~');
                }
            }
            pdo_commit();
            $this->json();
        } catch (Exception $e) {
            pdo_rollback();
            $this->json($e->getMessage(), 2);
        }
    }


    /**
     * 积分商城
     */
    public function shop()
    {
        $category = p_getall('integral_category', array('status' => 1), array(), array(), 'sort desc,id desc');

        if ($category) {
            foreach ($category as & $value) {
                $goods = p_getall('integral_goods', array('category_id' => $value['id'], 'is_delete' => 1, 'status' => 1), array(), array(), 'sort desc');
                foreach ($goods as $key => $val) {
                    if ($val['type'] == 2) {
                        if (empty($val['goods_name']) || empty($val['cover_image'])) {
                            $pdd = $this->bargain->pdd_details($val['relation_goods_id']);
                            $goods[$key]['goods_name'] = $pdd['goods_name'];
                            $goods[$key]['cover_image'] = $pdd['goods_thumbnail_url'];

                            p_update('integral_goods', array('goods_name' => $pdd['goods_name'], 'cover_image' => $pdd['goods_thumbnail_url']), array('id' => $val['id']));
                        }

                    } else {
                        $goods[$key]['cover_image'] = getImage($val['cover_image']);
                    }
                }
                $value['goods'] = $goods;
            }
        }

        $ad = $this->bargain->getAdvertisement(3);

        $config = array(
            'integral_name' => getConfig('integral_name', '积分')
        );
        $data = array(
            'category' => $category,
            'config' => $config,
            'ad' => $ad,
        );
        $this->json($data);
    }

}